package com.capgemini.wechat.service;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.capgemini.commons.CSVUtils;
import com.capgemini.core.PageList;
import com.capgemini.remind.pojo.OrderInfo;
import com.capgemini.wechat.mapper.SaleOrderMapper;

/**
 * 
 * @author
 * @date
 */
@Service
public class SaleOrderFileImportService extends FileImportBaseService {
	@Autowired
	private SaleOrderMapper saleOrderMapper;

	@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
	public void importSaleOrderCSV(String localFilePath) throws IOException {

		List<Map<String, String>> mapList = CSVUtils.readForMap(localFilePath + "/SaleOrder.csv", "UTF-8");
		if (null != mapList && !mapList.isEmpty()) {
			List<String> orderIds = new LinkedList<String>();
			for (Map<String, String> map : mapList) {

				map.put("UnitPrice", StringUtils.trimToNull( map.get("UnitPrice").replace(",", "")));
				map.put("LineDiscountAmount", StringUtils.trimToNull( map.get("LineDiscountAmount").replace(",", "")));
				map.put("Amount", StringUtils.trimToNull(map.get("Amount").replace(",", "")));

				if(!NumberUtils.isNumber(map.get("UnitPrice"))){
					map.put("UnitPrice", "0");
				}
				if(!NumberUtils.isNumber(map.get("LineDiscountAmount"))){
					map.put("LineDiscountAmount", "0");
				}
				if(!NumberUtils.isNumber(map.get("Amount"))){
					map.put("Amount", "0");
				}
				if(!orderIds.contains(map.get("SOID"))){
					orderIds.add(map.get("SOID"));
				}

			}
			int i = 0;
			for(; i < orderIds.size() / 1000; i++) {
				saleOrderMapper.removeExistingLines(orderIds.subList(1000*i, 1000*i + 1000));
			}
			if(orderIds.size() % 1000 > 0) {
				saleOrderMapper.removeExistingLines(orderIds.subList(1000*i, orderIds.size()));
			}
			for(i = 0; i < mapList.size() / 1000; i++) {
				saleOrderMapper.batchInsert(mapList.subList(1000*i, 1000*i + 1000));
			}
			if(mapList.size() % 1000 > 0) {
				saleOrderMapper.batchInsert(mapList.subList(1000*i, mapList.size()));
			}
		}
	}
}
